package com.socialsoftware.Page;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;
import androidx.appcompat.widget.Toolbar;

import com.socialsoftware.R;
import com.socialsoftware.api.ApiService;
import com.socialsoftware.api.ApiError;

import com.google.gson.Gson;
import com.socialsoftware.model.Contact;
import com.socialsoftware.util.AvatarUtil;
import com.socialsoftware.util.SessionManager;

import java.util.HashMap;
import java.util.Map;

/**
 * 好友申请页面
 * 发送好友申请并设置自我介绍、备注名和朋友权限
 */
public class FriendRequestActivity extends AppCompatActivity {

    private static final String TAG = "FriendRequestActivity";
    
    // UI组件
    private Toolbar toolbar;
    private ImageView ivAvatar;
    private TextView tvName;
    private TextView tvRegion;
    private TextView tvAccountId;
    private EditText etIntroduction;
    private TextView tvIntroductionCount;
    private EditText etRemark;
    private SwitchCompat switchMoments;
    private SwitchCompat switchLocation;
    private Button btnSend;
    
    // 数据
    private Contact contact;
    private SessionManager sessionManager;
    
    // 常量
    private static final int MAX_INTRODUCTION_LENGTH = 120;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_request);
        
        // 设置状态栏
        setStatusBar();
        
        // 初始化会话管理器
        sessionManager = SessionManager.getInstance(this);
        
        // 获取从搜索结果传递过来的联系人数据
        contact = getIntent().getParcelableExtra("contact");
        boolean fromQrScan = getIntent().getBooleanExtra("from_qr_scan", false);
        
        if (contact == null) {
            Toast.makeText(this, "获取联系人信息失败", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 检查是否已经是好友或已发送请求
        if (fromQrScan) {
            checkExistingFriendship(contact.getId());
        }
        
        // 初始化视图
        initViews();
        setupToolbar();
        displayContactInfo();
        setupListeners();
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        ivAvatar = findViewById(R.id.iv_avatar);
        tvName = findViewById(R.id.tv_name);
        tvRegion = findViewById(R.id.tv_region);
        tvAccountId = findViewById(R.id.tv_account_id);
        etIntroduction = findViewById(R.id.et_introduction);
        tvIntroductionCount = findViewById(R.id.tv_introduction_count);
        etRemark = findViewById(R.id.et_remark);
        switchMoments = findViewById(R.id.switch_moments);
        switchLocation = findViewById(R.id.switch_location);
        btnSend = findViewById(R.id.btn_send);
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("添加朋友");
        }
        
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
    }
    
    private void displayContactInfo() {
        // 设置头像
        ivAvatar.setImageDrawable(AvatarUtil.getGradientAvatar(this, contact.getRemark()));
        
        // 设置联系人信息
        tvName.setText(contact.getRemark());
        tvRegion.setText(contact.getRegion() != null ? contact.getRegion() : "未知地区");
        
        // 获取用户名（从remark字段中获取）
        String username = contact.getName();
        System.out.println(contact);
        

        
        // 设置账号显示
        if (username != null && !username.isEmpty()) {
            // 根据用户名格式显示不同前缀
            if (username.contains("@")) {
                tvAccountId.setText("邮箱: " + username);
            } else if (username.matches("\\d{11}")) {
                tvAccountId.setText("手机号: " + username);
            } else {
                tvAccountId.setText("账号: " + username);
            }
        } else {
            // 如果用户名为空，显示"未知账号"
            tvAccountId.setText("账号: 未知");
        }
        
        // 默认设置自我介绍
        String defaultIntro = "你好，我是" + sessionManager.getUserName();
        etIntroduction.setText(defaultIntro);
        updateIntroductionCount(defaultIntro.length());
        
        // 默认设置为备注名为对方名称
        etRemark.setText(contact.getRemark());
    }
    
    private void setupListeners() {
        // 设置自我介绍字数统计
        etIntroduction.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            
            @Override
            public void afterTextChanged(Editable s) {
                updateIntroductionCount(s.length());
            }
        });
        
        // 发送按钮点击事件
        btnSend.setOnClickListener(v -> {
            if (validateInput()) {
                sendFriendRequest();
            }
        });
    }
    
    private void updateIntroductionCount(int currentLength) {
        tvIntroductionCount.setText(currentLength + "/" + MAX_INTRODUCTION_LENGTH);
        
        // 超出字数限制时变为红色提示
        if (currentLength > MAX_INTRODUCTION_LENGTH) {
            tvIntroductionCount.setTextColor(getResources().getColor(android.R.color.holo_red_light));
        } else {
            tvIntroductionCount.setTextColor(getResources().getColor(android.R.color.darker_gray));
        }
    }
    
    private boolean validateInput() {
        String introduction = etIntroduction.getText().toString().trim();
        
        // 验证自我介绍长度
        if (introduction.length() > MAX_INTRODUCTION_LENGTH) {
            Toast.makeText(this, "自我介绍超出字数限制", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        // 验证自我介绍不为空
        if (TextUtils.isEmpty(introduction)) {
            Toast.makeText(this, "请填写自我介绍", Toast.LENGTH_SHORT).show();
            return false;
        }
        
        return true;
    }
    
    /**
     * 检查是否已经是好友或已发送请求
     * @param contactId 联系人ID
     */
    private void checkExistingFriendship(String contactId) {
        // 创建ApiService实例
        ApiService apiService = new ApiService(sessionManager);
        
        // 检查是否已经是好友
        apiService.checkFriendshipStatus(contactId, new ApiService.ApiCallback<Integer>() {
            @Override
            public void onSuccess(Integer status) {
                runOnUiThread(() -> {
                    switch (status) {
                        case 1: // 已经是好友
                            Toast.makeText(FriendRequestActivity.this, 
                                    "你们已经是好友了", Toast.LENGTH_SHORT).show();
                            finish();
                            break;
                        case 2: // 已发送请求，等待确认
                            Toast.makeText(FriendRequestActivity.this, 
                                    "已发送好友请求，等待对方确认", Toast.LENGTH_SHORT).show();
                            finish();
                            break;
                        case 3: // 对方发送了请求给你
                            Toast.makeText(FriendRequestActivity.this, 
                                    "对方已向你发送好友请求，请查看好友请求列表", Toast.LENGTH_SHORT).show();
                            // 打开好友请求列表
                            Intent intent = new Intent(FriendRequestActivity.this, FriendRequestsActivity.class);
                            startActivity(intent);
                            finish();
                            break;
                        case 0: // 没有关系，可以发送请求
                        default:
                            // 继续当前页面，允许发送请求
                            break;
                    }
                });
            }
            
            @Override
            public void onFailure(ApiError error) {
                // 如果API调用失败，我们继续当前流程，允许用户发送请求
                Log.e(TAG, "检查好友关系失败: " + error.getMessage());
                // 不做任何处理，继续当前页面
            }
        });
    }
    
    private void sendFriendRequest() {
        // 显示发送中状态
        btnSend.setEnabled(false);
        btnSend.setText("发送中...");
        
        // 获取当前用户名
        String currentUsername = sessionManager.getUserName();
        if (currentUsername == null) {
            Toast.makeText(this, "无法获取当前用户信息，请重新登录", Toast.LENGTH_SHORT).show();
            btnSend.setEnabled(true);
            btnSend.setText("发送");
            return;
        }
        
        // 构建好友请求数据
        Map<String, Object> requestData = new HashMap<>();
        Map<String, Object> requesterMap = new HashMap<>();
        Map<String, Object> addresseeMap = new HashMap<>();
        
        // 设置请求者（当前用户）- 使用username字段
        requesterMap.put("username", currentUsername);
        requestData.put("requester", requesterMap);
        
        // 设置接收者（要添加的好友）
        String contactId = contact.getId();
        String contactName = contact.getName();
        
        // 根据不同类型的ID设置不同的字段
        if (contactId != null && !contactId.isEmpty()) {
            // 设置username字段
            addresseeMap.put("username", contactName);
            
            // 尝试将ID转换为数字格式，如果是数字则设置为id字段
            try {
                Long id = Long.parseLong(contactId);
                addresseeMap.put("id", id);
            } catch (NumberFormatException e) {
                // 如果不是数字格式，则直接使用原始ID
                addresseeMap.put("id", contactId);
            }
            
            Log.d(TAG, "发送好友请求给: ID=" + contactId + ", 名称=" + contactName);
        } else {
            // 如果ID为空，则直接使用名称作为username
            addresseeMap.put("username", contactName);
            Log.d(TAG, "发送好友请求给: 名称=" + contactName);
        }
        
        requestData.put("addressee", addresseeMap);
        
        // 添加请求信息
        requestData.put("requesterNote", etIntroduction.getText().toString().trim());
        
        // 添加备注名称
        requestData.put("requestRemark", etRemark.getText().toString().trim());
        
        // 添加权限设置
        Map<String, Boolean> privacySettings = new HashMap<>();
        privacySettings.put("moments", switchMoments.isChecked());
        privacySettings.put("location", switchLocation.isChecked());
        privacySettings.put("profileInfo", true);  // 默认值
        privacySettings.put("lastSeen", true);     // 默认值
        privacySettings.put("phone", false);       // 默认值
        privacySettings.put("email", false);       // 默认值
        requestData.put("privacySettings", privacySettings);
        
        // 输出请求数据便于调试
        Log.d(TAG, "发送好友请求数据: " + new Gson().toJson(requestData));
        
        // 创建ApiService实例
        ApiService apiService = new ApiService(sessionManager);
        
        // 使用ApiService发送好友请求
        apiService.sendFriendRequest(requestData, new ApiService.ApiCallback<Map<String, Object>>() {
            @Override
            public void onSuccess(Map<String, Object> data) {
                runOnUiThread(() -> {
                    btnSend.setEnabled(true);
                    btnSend.setText("发送");
                    
                    Toast.makeText(FriendRequestActivity.this, 
                            "好友请求已发送，等待对方验证", Toast.LENGTH_LONG).show();
                    
                    // 返回到添加好友页面
                    finish();
                });
            }
            
            @Override
            public void onFailure(ApiError error) {
                runOnUiThread(() -> {
                    Log.e(TAG, "发送好友请求失败: " + error.getMessage());
                    
                    // 检查是否是因为已经是好友或已发送请求
                    if (error.getMessage().contains("already friends") || 
                        error.getMessage().contains("已经是好友")) {
                        Toast.makeText(FriendRequestActivity.this, 
                                "你们已经是好友了", Toast.LENGTH_SHORT).show();
                    } else if (error.getMessage().contains("pending request") || 
                               error.getMessage().contains("已发送请求")) {
                        Toast.makeText(FriendRequestActivity.this, 
                                "已发送好友请求，等待对方确认", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(FriendRequestActivity.this, 
                                "发送请求失败: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                    
                    btnSend.setEnabled(true);
                    btnSend.setText("发送");
                });
            }
        });
    }
    
    /**
     * 设置状态栏
     */
    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 设置状态栏文字和图标为深色
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            
            // 设置状态栏颜色为白色
            getWindow().setStatusBarColor(getResources().getColor(android.R.color.white));
        }
    }
} 